<?php
class Curl {

    private $client_key = NULL;
    private $client_secret = NULL;
    private $client_redirect_url = NULL;
    private $access_token = NULL;

    private $http_code = 0;

    public function __construct($config = array()) {
        if (empty($config)) {
            return;
        }

        $this->client_key = $config['key'];
        $this->client_secret = $config['secret'];

        if (isset($config['redirect_url'])) {
            $this->client_redirect_url = $config['redirect_url'];
        }

        if (isset($config['access_token'])) {
            $this->access_token = $config['access_token'];
        }
    }

    public function get($url, $params = array(), $is_json = false) {
        return $this->http($url, 'GET', $params, $is_json);
    }

    private function getHeader() {
      if (is_null($this->access_token)) {
        return 'Content_type: application/x-www-form-urlencoded';
      }

      return 'Authorization: Bearer ' . $this->access_token;
    }

    private function constructParams($method, $url, $params) {
        switch ($method) {
            case 'GET':
            case 'DELETE':
                $query_str = http_build_query($params);
                if (!empty($query_str)) {
                    $url .= '?' . $query_str;
                }
        }
        return $url;
    }

    private function getMethodOpts($method, $options, $params) {
        switch ($method) {
            case 'POST':
              $options[CURLOPT_POST] = TRUE;
              $options[CURLOPT_POSTFIELDS] = $params;
              break;

            case 'PUT':
              $options[CURLOPT_CUSTOMREQUEST] = 'PUT';
              $options[CURLOPT_POSTFIELDS] = $params;
              break;

            case 'DELETE':
              $options[CURLOPT_CUSTOMREQUEST] = 'DELETE';
              break;
        }

        return $options;
    }

    public function http($url, $method, $params = array(), $is_json = false) {
        $fp = curl_init();
        //construct params
        $url = $this->constructParams($method, $url, $params);

        $options = array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true, //only show data when calling echo methods
            CURLOPT_HEADER => false,

            CURLOPT_TIMEOUT => 30,
            CURLOPT_CONNECTTIMEOUT => 10
        );
        $options = $this->getMethodOpts($method, $options, $params);

        $headers = array();
        $headers[] = $this->getHeader();
        $headers[] = 'Expect:';
        $options[CURLOPT_HTTPHEADER] = $headers;

        curl_setopt_array($fp, $options);
        $result = curl_exec($fp);
        $is_json && ($result = json_decode($result, true));
        $this->http_code = curl_getinfo($fp, CURLINFO_HTTP_CODE);
        curl_close($fp);
        return $result;
    }

}
